<?php

namespace App\Http\Models\User;

use App\Http\Controllers\ApiController;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * App\Http\Models\User\UserBaseModel
 *
 * @property int $id
 * @property string $user_name 用户名
 * @property string $user_coin 用户余额
 * @property string $user_password 用户密码
 * @property string $user_salt 盐值
 * @property string $user_sign 签名
 * @property string $user_reg_time 注册时间
 * @property string $user_last_login_time 上次登录时间
 * @property string $user_birthday 生日
 * @property string $user_sex 性别 1男 2女
 * @property string $user_nickname 昵称
 * @property string $user_avatar 头像
 * @property string $user_token 令牌
 * @property string $union_id union_id
 * @property string $open_id open_id
 * @property string $is_push is_push
 * @property string $user_score 积分
 * @property string $defaultAddress 默认地址
 * @property string $is_first 是否首次充值 1首冲  0不是
 * @property string $Invite_code 邀请码
 * @property int $BNF_Lv1 上级  邀请受益人
 * @property int $BNF_Lv2 次级  邀请受益人
 * @property int $BNF_Lv3 三级  邀请受益人
 * @property int $BNF_Lv4 四级  邀请受益人
 * @property string $login_type 登录类型  WxLogin TxLogin mobile
 * @property int $is_disabled 是否禁用用户
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereBNFLv1($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereBNFLv2($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereBNFLv3($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereBNFLv4($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereDefaultAddress($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereInviteCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereIsDisabled($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereIsFirst($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereIsPush($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereLoginType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereOpenId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereUnionId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereUserAvatar($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereUserBirthday($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereUserCoin($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereUserLastLoginTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereUserName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereUserNickname($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereUserPassword($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereUserRegTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereUserSalt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereUserScore($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereUserSex($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereUserSign($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Http\Models\User\UserBaseModel whereUserToken($value)
 * @mixin \Eloquent
 */
class UserBaseModel extends Model
{
    public $table='user';
    public $timestamps = false;

    /**
     * @param $user_name
     * 返回1=已注册 2=未注册,3=密码错误如传入$user_password则是判断密码是否正确
     */
    public static function check_user($user_name,$user_password = false)
    {
        $user_info = self::where('user_name','=',$user_name)->select()->first();
        if($user_password)
        {
            if (empty($user_info))
            {
                return 2;
            }
            $input_password = md5( $user_password .$user_info->user_salt  );

            if ($input_password == $user_info->user_password)
            {
                return 1;
            }
            return 3;
        }
        return empty($user_info) ? 2 : 1;
    }

    /**
     * @param $userinfo
     * [
     *     必传参数 user_name,password
     * ]
     */
    public static function new_user($userinfo)
    {
        $user               = new UserBaseModel();
        $user->user_name    = $userinfo['user_name'];
        $user->user_coin   = 0;
        $user->user_salt    = rand(1000,9999);
        $user->user_password = md5($userinfo['user_password'] . $user->user_salt );
        $user->user_sign    = $userinfo['user_sign'] ? : '';
        $user->user_reg_time = time();
        $user->user_last_login_time = time();
        $user->user_birthday = $userinfo['user_birthday'] ? : 0;
        $user->user_sex = $userinfo['user_sex'] == '男' ? 1 : 2;
        $user->user_nickname = $userinfo['user_nickname'] ? : "暂时没有填写昵称";

        return $user->save() ? $user : false;

    }

    public static function checkUserName($nick)
    {

        $hasNickName = DB::table('user')->where('user_nickname',$nick)->select('user_nickname')->first();

        if (empty($hasNickName)){
            return true;
        }else{
            return false;
        }
    }



    public static function getUserBaseInfo($user_name)
    {
        $user_info = UserBaseModel::where('user_name','=',$user_name)->first();

        if (!empty($user_info)){
            return $user_info->toArray();
        }else{
            return false;
        }

    }



    /**
     * @param $user_info
     * @return array
     * 修改用户信息
     */
    public function checkUserInfo($user_info)
    {
        if (empty($user_info['uid'])){
            throw new \Error('uid为空');
        }

        $user = UserBaseModel::where('id','=',$user_info['uid'])->select()->first();

        if (empty($user)){
            return ['ret'=>-1,'data'=>null,'msg'=>'用户数据错误'];
        }

        $keys = ['user_avatar','user_nickname','user_sex','user_birthday','user_sign'];

        #检查空值
        foreach ($user_info as $idx=>$itm){
            #用户输入数据清洗
            $itm = strval($itm);
            $itm = htmlentities($itm);
            if (empty($itm) || $itm==''||$itm=='NULL'){
                return ['ret'=>-2,'data'=>null,'msg'=>$idx.'为空'];
            }
        }

        if (isset($user_info['user_sign'])&&empty($user_info['user_sign'])){
            return ['ret'=>-4,'data'=>null,'msg'=>'请填写签名'];
        }

        if (isset($user_info['user_sign'])&&mb_strlen($user_info['user_sign'],'utf-8')>30){
            return ['ret'=>-4,'data'=>null,'msg'=>'用户为空不能超过30个中文字符'];
        }


        if (isset($user_info['user_nickname'])){
            $has = self::checkUserName($user_info['user_nickname']);
            if ($has==false){
                return ['ret'=>-7,'data'=>null,'msg'=>'昵称已被使用'];
            }

        }

        if (isset($user_info['user_sex'])&&!in_array($user_info['user_sex'],[1,2])){
            return ['ret'=>-5,'data'=>null,'msg'=>'性别填写错误'];
        }

        if (isset($user_info['user_birthday'])&&strlen($user_info['user_birthday'])!=10){
            return ['ret'=>-6,'data'=>null,'msg'=>'出生日期必须是10位时间戳'];
        }

        $tmp = [];
        #过滤键值对 入库
        foreach ($keys as $key=>$val)
        {
            if (isset($user_info[$val])){
                $tmp[$val] = $user_info[$val];
            }
        }
        $row = UserBaseModel::where('id','=',$user_info['uid'])->update($tmp);
        if ($row !==false){
            return ['ret'=>200,'data'=>null,'msg'=>'修改成功'];
        }else{
            return ['ret'=>-3,'data'=>null,'msg'=>'修改失败'];
        }
    }


    public static function updateUser($uid,$data)
    {
        $row =DB::table('user')->where('id','=',$uid)->update($data);

        if ($row >=0){
            return ['ret'=>200,'data'=>null,'msg'=>'修改成功'];
        }else{
            return ['ret'=>-3,'data'=>null,'msg'=>'修改失败'];
        }
    }




    /**
     * @param $uid
     * @return mixed
     * 获取推送状态
     */
    public static function getPushStatus($uid)
    {
        $is_push = DB::table('user')->where('id',$uid)->select('is_push')->first();
        return $is_push;
    }


    /**
     * @param $uid
     * @param $is_push
     * @return mixed
     * 修改用户推送状态
     */
    public static function changePushStatus($uid, $is_push)
    {
        $is = DB::table('user')->where('id',$uid)->select('is_push')->update(['is_push'=>$is_push]);
        return $is;
    }


    /**
     * @param int $uid
     * @return string
     * 更新用户token
     */
    public static function updateToken(int $uid) : string
    {

        $Token =  ApiController::Token();
        $user                   = new UserBaseModel();
        $user::where('id',$uid)->update(['user_token'=>$Token]);
        return $Token;

    }
    
    public static function getUserInfoByToken(string $Token)
    {
        $user = self::where('user_token',$Token)->first();
        return $user;
    }
    



    public static function updateInviteCode(int $uid) : string
    {
        $InviteCode =  100000+$uid;
        $user                   = new UserBaseModel();
        $user::where('id',$uid)->update(['Invite_code'=>$InviteCode]);
        return $InviteCode;
    }


    /**
     * @return mixed
     * 获取反馈分类
     */
    public static function getFeedBackCate()
    {
        $data = DB::table('feedback_cate')->select('sug_cid','title')->get();
        return $data;
    }

    /**
     * @param $data
     * @return mixed
     * 新增反馈建议
     */
    public static function addSuggestion($data)
    {
        $time = time();
        $data['create_time'] = $time;
        $data['update_time'] = $time;
        $flag = DB::table('feedback')->insert($data);
        return $flag;
    }

    /**
     * @param $uid
     * @return mixed
     * 获取用户信息
     */
    public static function getUserInfo($uid)
    {

        $user = UserBaseModel::find($uid);
        if ($user){
            $user = $user->toArray();

            if (isset($user['user_password'])){
                $user['isset_pass'] = true;
                unset($user['user_password']);
            }else{
                $user['isset_pass'] = false;
            }


            unset($user['user_token']);
            unset($user['user_salt']);
        }
        return $user;
    }


    /**
     * @param $data
     * @return mixed
     * 微信首次登陆  自动注册用户
     */
    public static function WxReg($data)
    {
        $flag =  DB::table('user')->insertGetId($data);
        return $flag;
    }

    public static function TxReg($data)
    {
        $flag =  DB::table('user')->insertGetId($data);
        return $flag;
    }





    /**
     * @param $uid
     * @param $token
     * @param $headimgurl
     * @return mixed
     * 微信登陆  更新用户登陆信息
     */
    public static function updateWxLoginInfo($uid, $token, $headimgurl)
    {
        $data = [
            'user_token'                    => $token,
            'user_last_login_time'          => time(),
            'user_avatar'                   => $headimgurl
        ];

        $flag =  DB::table('user')->where('id',$uid)->update($data);
        return $flag;
    }


    public static function updateTxLoginInfo($uid, $token, $headimgurl)
    {
        $data = [
            'user_token'                    => $token,
            'user_last_login_time'          => time(),
            'user_avatar'                   => $headimgurl
        ];

        $flag =  DB::table('user')->where('id',$uid)->update($data);
        return $flag;
    }




    /**
     * @param $uid
     * @param $to_uid
     * @return array
     * 添加关注
     */
    public static function addFollow($uid, $to_uid)
    {
        $res = DB::table('follow')->where('uid',$uid)->where('to_uid',$to_uid)->first();
        $res = get_object_vars($res);
        if (empty($res)){
            #为空 尚未有记录添加记录
           $flag = DB::table('follow')->insert(['uid'=>$uid,'to_uid'=>$to_uid,'status'=>1]);
           return ['status'=>$flag];
        }else{
           #已有记录  且状态为取消关注 可以修改状态 为 已关注
            if ($res['status'] == 0){
                $flag = DB::table('follow')->where('uid',$uid)->where('to_uid',$to_uid)->update(['status'=>1]);
                return ['status'=>$flag];
            }else{
                return ['status'=>'3','msg'=>'已关注对方无需再次添加'];
            }
        }
    }


    /**
     * @param $uid
     * @param $to_uid
     * @return array
     * 取消关注
     */
    public static function cancelFollow($uid, $to_uid)
    {
        $res = DB::table('follow')->where('uid',$uid)->where('to_uid',$to_uid)->first();
        $res = get_object_vars($res);
        if (empty($res)){
            return ['status'=>false,'msg'=>'用户数据不存在'];
        } elseif ($res['status']==0){
            return ['status'=>false,'msg'=>'尚未关注，无法操作'];
        }else{
            $flag = DB::table('follow')->where('uid',$uid)->where('to_uid',$to_uid)->update(['status'=>0]);
            if ($flag !==false)
                return ['status'=>$flag,'已取消关注'];
            else
                return['status'=>$flag,'网络错误，操作失败'];
        }
    }


    public static function getMyFollow($uid,$search=false)
    {
        $myFollow = DB::table('follow as a')
            ->select(DB::raw("case when 2cy_b.to_uid = '".$uid."' then 'mutual_follow' else 'my_follow' END AS follow,2cy_a.to_uid as editer_uid,2cy_c.user_nickname,2cy_c.user_sign,2cy_c.user_avatar,2cy_c.id"))
            ->leftJoin('follow AS b','a.to_uid','=','b.uid')
            ->leftJoin('user AS c','a.to_uid','=','c.id')
            ->where('a.uid','=',$uid)
            ->where('a.status','1')
            ->where(function ($query) use ($uid)
            {
                $query->where('b.status', '=', 1)->orwhereNull('b.status');
            })
        ->groupBy("a.to_uid");


        if ($search)
        {
            $myFollow = $myFollow->where('c.user_nickname','like',"%$search%")->get();
        }
        else
        {
            $myFollow = $myFollow->get();
        }
        return $myFollow;

    }

    public static function getMyfans($uid,$search=false)
    {
        //查出关注我的
        $myFans = DB::table("follow")->leftJoin("user",'user.id','=','follow.uid')->where('to_uid',$uid)->where('status','1')
            ->select(DB::raw("2cy_follow.*,2cy_user.user_nickname,2cy_user.user_sign,2cy_user.user_avatar,2cy_user.id as editer_uid"));
        if ($search)
        {
            $myFans = $myFans->where("user.user_nickname",'like',"%$search%")->get();
        }
        else
        {
            $myFans = $myFans->get();
        }
        if (!empty($myFans))
        {
            foreach ($myFans as &$value)
            {
                //查查关注我的uid有没有被我关注
                $value->follow = empty(DB::table("follow")->where('uid',$uid)->where('to_uid',$value->uid)->where('status','1')->select()->first()) ? 'follow_me' : "mutual_follow";
            }
        }

        return $myFans;

    }

    public static function getFollowSearch($uid,$keyWords)
    {
        return self::getMyFollow($uid,$keyWords);
    }



    public static function addAddress(array $data)
    {
        $columns = Schema::getColumnListing('address');

        foreach ($data as $k=>$v){
            if (!in_array($k,$columns)&&$k){
               unset($data[$k]);
            }
            $set = ['provice','city','dist','content'];
            if (in_array($k,$set)){
               $len = mb_strlen($data[$k]);
               if($len>255){
                   return ['data'=>null,'ret'=>'-9','msg'=>'超出255字符长度限制'];
               }
            }
        }
        $data['create_time'] =$data['update_time'] = time();
        $flag = DB::table('address')->insert($data);

        if ($flag>0){
            return ['data'=>null,'ret'=>'200','msg'=>'添加成功'];
        }else
            return ['data'=>null,'ret'=>'-8','msg'=>'添加失败'];
    }


    public static function editAddress(array $data)
    {
        $columns    = Schema::getColumnListing('address');
        $address_id = $data['address_id'];

        $has = DB::table('address')->where('id',$address_id)->first();
        if(empty($has)){
            return ['data'=>null,'ret'=>'-11','msg'=>'地址不存在'];
        }

        foreach ($data as $k=>$v){
            if (!in_array($k,$columns)&&$k){
                unset($data[$k]);
            }
            $set = ['provice','city','dist','content'];
            if (in_array($k,$set)){
                $len = mb_strlen($data[$k]);
                if($len>255){
                    return ['data'=>null,'ret'=>'-9','msg'=>'超出255字符长度限制'];
                }
                if (empty($data[$k])){
                    return ['data'=>null,'ret'=>'-10','msg'=>'请填写'.$k];
                }
            }
        }
        $data['update_time'] = time();
        $flag = DB::table('address')->where('id',$address_id)->update($data);

        if ($flag>0){
            return ['data'=>null,'ret'=>'200','msg'=>'修改成功'];
        }else
            return ['data'=>null,'ret'=>'-8','msg'=>'修改失败'];
    }


    public static function getAddressById($uid)
    {
        $data = DB::table('address')->where('uid',$uid)->select()->get();
        return $data;
    }


    public static function getAddressByAddressId($address_id)
    {
        $data = DB::table('address')->where('id',$address_id)->first();
        return $data;
    }

    public static function delAddress($id,$uid)
    {
        $data = DB::table('address')->where('uid',$uid)->whereIn('id',$id)->delete();
        return $data;
    }


    public static function getComplainCate()
    {
        $data = DB::table('game_complain_cate')->select()->get();
        return $data;
    }


    public static function addGameComplain($data)
    {
        $data['create_time']    = $data['update_time'] = time();
        unset($data['token']);
        $data['status']         = '已提交';
        $id                     =  DB::table('game_complain')->insertGetId($data);
        return $id;
    }

    public static function queryIsComplain($game_id)
    {
        $data = DB::table('game_complain')->where('game_id',$game_id)->get();
        return $data;
    }



    public static function getVersion()
    {
        $data = DB::table('version')->orderBy('id','desc')->first();
        return $data;
    }


    public static function setDefaultAddress($uid,$id)
    {
        $user = UserBaseModel::where('id',$uid)->select()->first();
        if (empty($user)){
            return false;
        }
        $user->defaultAddress = $id;
        $res = $user->save();
        return $res;
    }


    public static function getUser($uid)
    {
        $user = UserBaseModel::where('id',$uid)->select()->first();
        if (empty($user)){
            return false;
        }
        return $user->toArray();
    }

    public static function getUserList($uid)
    {
        $user = UserBaseModel::whereIn('id',$uid)->select()->get();
        if (empty($user)){
            return false;
        }
        return $user->toArray();
    }


    public static function addCoin($uid,$coin,$score)
    {
//        Cache::store('redis')->remember();
        $user = self::find($uid);
        $user->user_coin        = $user->user_coin+$coin;
        $user->user_score       = $user->user_score+$score;
        $user->is_first         = 0;
        $res = $user->save();
        return $res;
    }


    public static function bindInviteCode($uid,$invite_id)
    {
        $flag = self::where('id',$uid)->update(['f1'=>$invite_id]);
        return $flag;
    }

    public static function getUserByInviteCode($code)
    {
        $user = self::where('Invite_code',$code)->first();
        return $user;
    }












































}
